package org.phalanx.servlet.webmessages;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.phalanx.messenging.Messageable;
import org.phalanx.messenging.QueryMessage;
import org.phalanx.server.PhalanxServer;
import org.phalanx.server.ServerCache.CacheManager;
import org.phalanx.server.user.PhalanxUser;
import org.phalanx.servlet.websession.UserWebSessionManager;

public class GamesChatInfoContext implements WebMessageable {
	private PhalanxServer pServer;
	public static final String GAMES_CHAT_CONTEXT = "gameschatinfo";
	
	public GamesChatInfoContext(PhalanxServer pServer){
		this.pServer = pServer;
	}
	
	@Override
	public void onContextLoadable(String context, Cookie authCookie,
			HttpServletRequest req, HttpServletResponse resp) {
		if (context.equals(GAMES_CHAT_CONTEXT)){
			CacheManager cacheMgr = pServer.getCacheManager();
			PhalanxUser u = (PhalanxUser)cacheMgr.getElement("TokenSessionCache", authCookie.getValue());
			
			if (u != null){
				UserWebSessionManager session = new UserWebSessionManager(cacheMgr);
				
				String query = req.getParameter("query");
				
				if (query != null && query.equals("chat")){
					QueryMessage q = new QueryMessage();
					q.setQueryInfo("chat");
					q.setQueryInfoValue("5");
					sendGamesChatResponse(q, u.getId(), session);
				}
				else if (query != null && query.equals("games")){
					QueryMessage q = new QueryMessage();
					q.setQueryInfo("games");
					q.setQueryInfoValue("10");
					sendGamesChatResponse(q, u.getId(), session);
				}
			}
		}
	}
	
	private void sendGamesChatResponse(Messageable m, Integer uid, UserWebSessionManager session){
		session.sendMessage(uid, m);
	}

}
